/** 
 * 注意注意：embed本地浏览器打开会有跨域问题（跨域无法操作子dom）
 * 如果想本地打开有效，需要把svg代码copy到index.html中 * 
 * 使用服务(如tomcat或iis)打开，则没有 
 * 
 */ 
var SVG = {
    // 宽高对应svg 的 viewBox属性
    svgWidth: 572,
    svgHeight: 694,
    setMarker: function(data) {
        const embed = document.querySelector('#embed')
        const doc = this.getSubDocument(embed)
        this.clearMarker()
        var self = this
        
        data.forEach(item => {
            const name = item.name
            const value = item.value
            const targetEl = self.getTargetByname(doc, name)
            const targetText = targetEl.querySelector('.text-map')
            // 获取相对坐标
            let x = Number(targetText.getAttribute('x'))
            let y = Number(targetText.getAttribute('y'))
           

            console.info(x, y)

            x = x / self.svgWidth * 100
            y = y / self.svgHeight * 100

            const left =  x + '%'
            const bottom = y + '%'
            const css = {
                left: left,
                top: bottom
            }

            self.addMarker(item, css)
        })
    },
    addMarker(item, css) {
        const html = []
        html.push('<div class="map-marker">')
        html.push('<span>'+item.value+'</span>')
        html.push('</div>')

        const str = html.join('')
        const $html = $(str)
        $html.css(css)
        
        $('#svg-wrap').append($html)
    },
    clearMarker() {
        const markers = document.querySelectorAll('.map-marker')
        Array.prototype.forEach.call(markers, function(item) {
            item.remove()
        })
    },
    getTargetByname(doc, name) {
        
        return doc.querySelector('[attr="' + name + '"]')
    },
    getSubDocument(embedding_element){
        if (embedding_element.contentDocument) {
            return embedding_element.contentDocument;
        } 
        else  {
            var subdoc = null;
            try {
                subdoc = embedding_element.getSVGDocument();
            } catch(e) {}
            return subdoc;
        }
    }
}